package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"mock/stream_grpc_test/proto"
	"sync"
	"time"
)

func main() {
	conn, err := grpc.Dial("127.0.0.1:8888", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	//服务端流模式
	client := proto.NewGreeterClient(conn)
	stream, err := client.GetStream(context.Background(), &proto.StreamReqData{Data: "mock"})
	if err != nil {
		panic(err)
	}
	for {
		data, err := stream.Recv()
		if err != nil {
			fmt.Println(err)
			break
		}
		fmt.Println(data.Data)
	}
	//客户端流模式
	putStream, _ := client.PutStream(context.Background())
	i := 0
	for {
		i++
		_ = putStream.Send(&proto.StreamReqData{Data: fmt.Sprintf("慕课网%d", i)})
		time.Sleep(time.Second)
		if i > 10 {
			break
		}
	}
	//双向流模式
	allStream, err := client.AllStream(context.Background())

	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		defer wg.Done()
		for {
			recv, _ := allStream.Recv()
			fmt.Println("收到客户端消息：" + recv.Data)
		}

	}()

	go func() {
		defer wg.Done()
		for {
			allStream.Send(&proto.StreamReqData{Data: "mock"})
			time.Sleep(time.Second)
		}
	}()

	wg.Wait()
}
